//index.js
//获取应用实例
var api = require("../../api.js"),
  r = "",
  inviteOpenId = '',
  app = getApp();

Page({
  data: {
    tabbar: {},
    swiperH: "",
    pageIndex: 1,
    currentTab: 0, //预设当前项的值
    currentIndex: 0,
    nowIdx: 0, //当前swiper索引
    imgList: [], //轮播组件
    indexArr: [],
    tradeData: [],
    articles: [],
    classRoom: [],
    windowHeight: 0, //视图高度
  },
  onLoad: function(options) {
    r = this;
    app.editTabbar();
    /** 缓存 opne_id  */
    getApp().get_open_id();
    /** 邀请人的id */
    inviteOpenId = options.inviteOpenId;
    if (options.shareType != 7 && options.shareType) {
      app.globalData.shareType = options.shareType;
      app.globalData.userId = options.id;
    } else {
      /** 存入缓存中 */
      wx.setStorageSync('inviteOpenId', options.inviteOpenId);
    }
    //app.getWxUserInfo().then(res => {
    app.globalData.shareType = '';
    app.globalData.userId = '';
    if (options.shareType) {
      setTimeout(() => {
        if (options.shareType == 0) {
          wx.navigateTo({
            url: `../activedetial/activedetial?id=${options.id}&inviteOpenId=${options.inviteOpenId}&inviteType=1`
          });
        } else if (options.shareType == 1) {
          wx.navigateTo({
            url: `../art/art?id=${options.id}`
          });
        } else if (options.shareType == 2) {
          wx.navigateTo({
            url: `../classdetail/classdetail?id=${options.id}&inviteOpenId=${options.inviteOpenId}`
          });
        } else if (options.shareType == 7) {
          wx.navigateTo({
            url: `../activedetial/activedetial?id=${options.id}&inviteOpenId=${options.inviteOpenId}&inviteType=2`
          });
        }
      }, 800);
    }
    //}).catch(error => { })
    r.initData(); //初始化数据
  },
  //获取swiper高度
  getHeight: function(e) {
    var winWid = wx.getSystemInfoSync().windowWidth - 2 * 25; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width;
    // console.log(winWid, imgh, imgw);
    var sH = (winWid * imgh) / imgw + "px";
    // console.log(r);
    r.setData({
      swiperH: sH
    });
  },
  imageLoad: function(e) {
    var $width = e.detail.width, //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height; //图片的真实宽高比例
    var viewWidth = 675, //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 675 / ratio; //计算的高度值
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    r.setData({
      viewWidth: viewWidth,
      viewHeight: 'auto'
      // viewHeight: viewHeight
    });
  },
  //swiper滑动事件
  swiperChange: function(e) {
    console.log(e);
    this.setData({
      nowIdx: e.detail.current
    });
  },
  //跳转到详情页
  goDetails: function(e) {
    var o = e.currentTarget.dataset;
    var openid = getApp().globalData.wxUserInfo.openId;
    /** 邀请人的 open_id */
    var inviteOpenId = wx.getStorageSync('inviteOpenId');
    console.log('inviteOpenId = ' + inviteOpenId)
      if (o.type == 1) {
        wx.navigateTo({
          url: `../activedetial/activedetial?id=${o.id}`
        });
      } else if (o.type == 2) {
        wx.navigateTo({
          url: "../art/art?id=" + o.id
        });
      } else {
        wx.navigateTo({
          url: "../classdetail/classdetail?id=" + o.id
        });
      }
  },
  gotail(e) {
    var o = e.currentTarget.dataset;
    wx.navigateTo({
      url: `../discoverdetail/discoverdetail?id=${o.id}`
    });
  },
  onReady: function() {
    wx.hideTabBar({
      fail: function() {
        setTimeout(function() {
          wx.hideTabBar();
        }, 500);
      }
    });
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        var windowHeight = res.windowHeight;
        let h = 750 * res.windowHeight / res.windowWidth - 198;
        //两列，每列的图片宽度
        var height = (windowHeight - 100);
        r.setData({
          windowHeight: h,
        });
      },
    })
  },
  initData: function() {
    wx.showLoading({
      title: "数据加载中"
    });
    if (r.data.currentTab == 0) { /** 推荐页显示 */
      for (let i = 0; i < 4; i++) {
        // const indexArr = 'indexArr'+i;
        app.getData.index(i).then(res => {
          const indexArr = res.data.data;
          if (i == 0) {
            r.setData({
              indexArr0: indexArr
            })
          } else if (i == 1) {
            r.setData({
              indexArr1: indexArr ? indexArr : ''
            })
          } else if (i == 2) {
            r.setData({
              indexArr2: indexArr
            })
          } else if (i == 3) {
            r.setData({
              indexArr3: indexArr
            })
          }
          if (i == 3) {
            setTimeout(() => {
              wx.hideLoading();
            }, 500)
          }
        })
      }
    } else if (r.data.currentTab == 1) { /** 活动页 */
      const t = new Object();
      t.pageIndex = 1, t.pageSize = 5;
      //获取每日一案例板块内容
      app.getData.activities(t).then(res => {
        var t = res.data;
        if (t.length != 0) {
          setTimeout(function() {
            wx.hideLoading();
            var checkStatus = '';
            t.length == 5 ? checkStatus = true : false;
            r.setData({
              tradeData: t,
              loading: checkStatus,
              loadingComplete: !checkStatus,
            });
          }, 1000);
        } else {
          wx.hideLoading();
          setTimeout(() => {
            r.setData({
              tradeData: [],
              loadingComplete: false,
              loading: false,
              // hidden:true
            })
          }, 500)
        }
      }).catch(res => {
        console.log(res)
      })
    } else if (r.data.currentTab == 2) {
      const t = new Object();
      t.pageIndex = 1;
      t.pageSize = 5;
      app.getData.articles(t).then(res => {
        setTimeout(() => {
          wx.hideLoading();
          r.setData({
            articles: res.data
          })
        }, 550);

      })
    } else {
      wx.request({
        url: api.cou.courses,
        success: function(res) {
          if (res.statusCode == 200 && res.data.code == 200) {
            wx.hideLoading();
            r.setData({
              classRoom: res.data.data
            });
          }
        }
      });
    }
    // 获取banner列表
    // var typeNum = Number(r.data.currentTab) + 1;
    // console.log(typeNum)
    // wx.request({
    //   url: api.banner.getBanner + "/" + typeNum,
    //   header: {
    //     "content-type": "application/x-www-form-urlencoded" // 默认值
    //   },
    //   success: function(res) {
    //     if (res.statusCode == 200 && res.data.code == 200) {
    //       // console.log(res.data.data);
    //       r.setData({
    //         imgList: res.data.data
    //       });
    //     }
    //   }
    // });
  },
  loading: function() {
    var t = new Object();
    t.pageIndex = r.data.pageIndex;
    t.pageSize = 5;
    if (r.data.currentTab == 1) {
      app.getData.activities(t).then(res => {
        console.log(res)
        const n = res.data;
        if (n.length > 0) {
          var dataList = r.data.tradeData.concat(n);
          setTimeout(() => {
            wx.hideLoading();
            r.setData({
              tradeData: dataList,
              loading: true,
              loadingComplete: false,
            });
          }, 1000);
        } else {
          setTimeout(() => {
            wx.hideLoading();
            r.setData({
              loading: false,
              loadingComplete: true,
            });
          }, 1000);
        }

      });
    } else {
      app.getData.articles(t).then(res => {
        console.log(res)
        const n = res.data;
        if (n.length > 0) {
          var dataList = r.data.articles.concat(n);
          setTimeout(() => {
            wx.hideLoading();
            r.setData({
              articles: dataList,
              loading: true,
              loadingComplete: false,
            });
          }, 1000);
        } else {
          setTimeout(() => {
            wx.hideLoading();
            r.setData({
              loading: false,
              loadingComplete: true,
            });
          }, 1000);
        }

      });
    }
  },
  loadMoreData: function() {
    let _that = this
    // console.log(_that.data.loading)
    if (_that.data.loading && (_that.data.currentTab == 1 || _that.data.currentTab == 2)) {
      _that.setData({
        pageIndex: _that.data.pageIndex + 1,
      });
      _that.loading();
    };

  },
  onPageScroll: function(e) {
    //  console.log(e)
  },
  swichNav: function(e) {
    // console.log(e)
    var currentTab = e.target.dataset.current;
    if (r.data.currentTab == currentTab) {
      return false;
    }
    r.setData({
      currentTab: currentTab,
      pageIndex: 1,
      scrollTop: 0
    });
  },
  // 滚动切换标签样式
  switchTab: function(e) {
    // console.log(e)
    if (e.detail.source == 'touch') {
      r.setData({
        currentTab: e.detail.current,
        pageIndex: 1,
        scrollTop: 0
      })
    }
    // r.setData({
    //   currentTab: e.detail.current,
    //   nowIdx: 0
    // });
    r.initData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading(), console.log("下拉刷新"), r.initData();
    setTimeout(function() {
      wx.hideNavigationBarLoading(), wx.stopPullDownRefresh();
    }, 1500);
  },

});